import axios from 'axios'
import router from "@/router";
import {message} from "@/element/message";

// 请求接口域名
axios.defaults.baseURL = "http://docker.larabbs.com/api/"

// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('user')) {
            let user = JSON.parse(localStorage.getItem('user'))
            config.headers.Authorization = user.api_token
            config.headers.UserId = user.id
        }
        /*if (store.state.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = `token ${store.state.token}`;
        }*/
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 300: // 重新登录
                    message(error.response.data.msg, 'warning')
                    // 清除缓存并跳转到登录地址
                    localStorage.removeItem('user')
                    router.push({
                        path:'/login'
                    })
                    break
                case 400:
                    message(error.response.data.msg, 'warning')
                    break
                case 500:
                    message('API错误', 'error')
                    break
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的信息
    });